import { ReactNode } from "react";
import {
  Box,
  Button,
  Typography,
  TextField,
  TextFieldProps,
} from "@mui/material";
import { RegisterOptions, useForm } from "react-hook-form";

type Option = {
  name: string;
  setting?: RegisterOptions;
} & TextFieldProps;

export type FormProps = {
  title: string;
  btnTitle: string;
  onSubmit: any;
  options: Option[];
  children?: ReactNode;
  sx?: any;
};

export default function Form({
  title,
  btnTitle,
  onSubmit,
  options,
  children,
  sx = {},
}: FormProps) {
  const { register, watch, handleSubmit, formState } = useForm();
  return (
    <>
      <Typography variant="h5" component="h3">
        {/* 表单标题 */}
        {title}
      </Typography>
      <Box
        component="form"
        noValidate
        onSubmit={handleSubmit(onSubmit)}
        sx={{
          "& > :not(style)": { my: 2 },
        }}
      >
        {options.map(({ name, setting, ...other }) => (
          <TextField
            key={name}
            {...register(name, setting)}
            {...other}
            fullWidth
            variant="outlined"
          />
        ))}
        {children}
        <Button type="submit" variant="contained" fullWidth>
          {btnTitle}
        </Button>
      </Box>
    </>
  );
}
